<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/28
 * Time: 9:21
 */

namespace App\Game\Traits;

use Crypt_RSA;
use Carbon\Carbon;

trait SaTrait
{
    /**
     * gameapi
     * 2018/9/24 13:55
     * Administrator
     * getSign
     * 生成签名
     * @param $plaintext
     * @return string
     */
    public function getSign($plaintext)
    {
        $rsa = new Crypt_RSA();
        $rsa->loadKey($this->privateKey);//xxx 私钥匙
        $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
        $rsa->setHash("md5");
        $signature = $rsa->sign($plaintext);
        return base64_encode($signature);
    }

    /**
     * gameapi
     * 2018/9/24 13:55
     * Administrator
     * agRequest
     * 封装ag得请求
     * @param $action
     * @return string
     */
    public function saRequest($action)
    {
        $timestamp = Carbon::now()->timestamp;
        $signature = $this->getSign($this->channelId . $this->thirdParty . $this->tag . $timestamp);
        $json = [
            'json' => [
                'requestId' => str_random(10),
                'channelId' => $this->channelId,
                'thirdParty' => $this->thirdParty,
                'tag' => $this->tag,
                'action' => $action,
                'live' => 1,
                'timestamp' => $timestamp,
                'signature' => $signature
            ]
        ];

        $result = $this->request('POST', $this->gameUrl, [], $this->header, $json);
        return $result;
    }

    public function apiDataParse(array $apiData, array $data)
    {
        $data = $this->usernamePre($data);
        return $data;
    }

    private function usernamePre(array $data)
    {
        if (array_key_exists('username', $data)) {
            $data['username'] = $this->pre . $data['username'];
        }
        return $data;
    }
}